var query = require('../../common').Query;
var map = require('../../common').Mapping;
var mailer = require('../../common').Mailer;
var PythonShell = require('python-shell');
var fs = require('fs');

var MAX_W8 = 86400000;

exports.findPlanPage = function (req, res) {
    var obj = map.generateNavBar(req);
    var param = {};
    if (req.query.plan_id) {
        param.plan_id = req.query.plan_id;
    } else {
        param.status = "latest";
    }
    query(map.sql.findPlan, res, param, function (rows) {
        if (rows.length == 1) {
            obj.plan = rows[0];
            res.render("planIndex", obj);
        } else {
            obj.plan = {};
            res.render("planIndex", obj);
        }
    });
};

exports.addPlanPage = function (req, res) {
    var obj = map.generateNavBar(req);
    query("SELECT * FROM setting WHERE s_id = 1", res, {}, function (rows) {
        obj.setting = rows[0];
        res.render("adminAddPlan", obj);
    });
};

exports.inputPlanPage = function (req, res) {
    var obj = map.generateNavBar(req);
    obj.self = req.session.uid;
    query(map.sql.findMemberList, res, {leader: req.session.uid}, function (rows) {
        obj.members = rows;
        res.render("managerInputPlan", obj);
    });
};

exports.findPlans = function (req, res) {
    query(map.sql.findPlan, res, req.body, function (rows) {
        res.send(rows);
    });
};

exports.findPlanList = function (req, res) {
    query(map.sql.findPlanList, res, req.body, function (rows) {
        res.send(rows);
    });
};

exports.planListPage = function (req, res) {
    res.render("findPlan", map.generateNavBar(req));
};

exports.addPlan = function (req, res) {
    req.body.start_date = new Date(req.body.start_date).Format('yyyy-MM-dd');
    req.body.end_date = new Date(req.body.end_date).Format('yyyy-MM-dd');
    req.body.updatedAt = new Date().Format('yyyy-MM-dd hh:mm');
    query("UPDATE plan SET status = 'history' WHERE status <> 'history'", res, {}, function () {
        query(map.sql.addPlan, res, req.body, function () {
            query("SELECT email FROM `user` WHERE role='manager'", {}, {}, function (addrs) {
                var addr = "";
                addrs.forEach(function (e) {
                    addr += (e.email + ";");
                });
                mailer({
                    sendTo: addr, html: "各位研发组长:<br />" +
                    "&nbsp;&nbsp;大家好!新的双周计划(" + req.body.plan_name + ")已发布,请于截止日期:<span style='color: red'>"
                    + req.body.end_date + "</span>之前登陆系统填写计划安排"
                });
                res.send("success");
            });
        });
    });
};

exports.editPlan = function (req, res) {
    req.body.updatedAt = new Date().Format('yyyy-MM-dd hh:mm');
    query(map.sql.editPlan, res, req.body, function (rows) {
        if (rows.affectedRows != 0) {
            res.send("success");
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.exportDoc = function (req, res) {
    var docData = {
        total: 0,
        groupProject: [],
        groupManager: [],
        extraRisk: {},
        extraGrown: {},
        extraOtherInfo: {}
    };
    var projectMap = {};
    var teamDetail = {};

    //step1. prepare project map data
    query("SELECT p_id,p_name FROM project", res, {}, function (data) {
        data.forEach(function (e) {
            projectMap[e.p_id] = e.p_name;
        });
        projectMap.inactive = "已删除";
        fillProjectGroup();
    });

    //step2. fill project group data
    function fillProjectGroup() {
        var length = 0;
        query(map.sql.findPlanDetailByProject, res, {plan_id: req.params.id}, function (rows) {
            for (var i = 0; i < rows.length; i++) {
                docData.total += rows[i].percentage;
                rows[i].status = map.projectStatus[rows[i].status];
                !rows[i].status && (rows[i].status="已删除");
                rows[i].project_pm = map.userName[rows[i].project_pm];
                rows[i].project_leader = map.userName[rows[i].project_leader];
                if (i == 0 || rows[i - 1].p_id != rows[i].p_id) {
                    docData.groupProject.push({
                        name: rows[i].p_name,
                        leader: rows[i].project_leader == rows[i].project_pm ? (rows[i].project_leader) : (rows[i].project_pm + "/" + rows[i].project_leader),
                        date: rows[i].start_date.Format('yyyy-MM-dd') + "~" + rows[i].end_date.Format('yyyy-MM-dd'),
                        status: rows[i].status
                    });
                    length++;
                }
                !docData.groupProject[length - 1].detail && (docData.groupProject[length - 1].detail = []);
                !docData.groupProject[length - 1].total && (docData.groupProject[length - 1].total = 0.0);
                docData.groupProject[length - 1].detail.push(map.userName[rows[i].fk_usr] + '(' + rows[i].percentage * 100
                    + "%" + (map.userRole[rows[i].fk_usr] == 'intern' ? " 实习" : "") + ")");
                docData.groupProject[length - 1].total += rows[i].percentage;
            }
            fillManagerGroup();
        });
    }

    //step3. fill leader group data
    function fillManagerGroup() {
        var length = 0;
        query(map.sql.findPlanDetailByManager, res, {plan_id: req.params.id}, function (rows) {
            query(map.sql.findMemberList, res, {role: ["member", "intern"]}, function (data) {
                data.forEach(function (e) {
                    if (e.manager) {
                        !teamDetail[map.userName[e.manager]] && (teamDetail[map.userName[e.manager]] = []);
                        teamDetail[map.userName[e.manager]].push(map.userName[e.u_id]);
                    }
                });

                for (var i = 0; i < rows.length; i++) {
                    if (i == 0 || rows[i - 1].leader != rows[i].leader) {
                        docData.groupManager.push({leader: map.userName[rows[i].leader]});
                        length++;
                    }
                    docData.groupManager[length - 1].team = teamDetail[docData.groupManager[length - 1].leader];
                    !docData.groupManager[length - 1].team && (docData.groupManager[length - 1].team = "");
                    !docData.groupManager[length - 1].detail && (docData.groupManager[length - 1].detail = {});
                    !docData.groupManager[length - 1].detail[projectMap[rows[i].fk_prj]] &&
                    (docData.groupManager[length - 1].detail[projectMap[rows[i].fk_prj]] = []);
                    docData.groupManager[length - 1].detail[projectMap[rows[i].fk_prj]].push(map.userName[rows[i].fk_usr]
                        + '(' + rows[i].percentage * 100 + "%" + (map.userRole[rows[i].fk_usr] == 'intern' ? " 实习" : "") + ")");
                }

                query('SELECT type,content,fk_pm FROM plan_extra WHERE fk_plan=#id ORDER BY fk_pm', res, req.params, function (extra) {
                    var items = [{},{},{}];
                    extra.forEach(function (e) {
                        if (e.type == 'risk') {
                            !items[0][e.fk_pm] && (items[0][e.fk_pm] = 0);
                            items[0][e.fk_pm]++;
                            !docData.extraRisk[map.userName[e.fk_pm]] && (docData.extraRisk[map.userName[e.fk_pm]] = []);
                            docData.extraRisk[map.userName[e.fk_pm]].push(items[0][e.fk_pm] + ". " + e.content);
                        } else if (e.type == 'training') {
                            !items[1][e.fk_pm] && (items[1][e.fk_pm] = 0);
                            items[1][e.fk_pm]++;
                            !docData.extraGrown[map.userName[e.fk_pm]] && (docData.extraGrown[map.userName[e.fk_pm]] = []);
                            docData.extraGrown[map.userName[e.fk_pm]].push(items[1][e.fk_pm] + ". " + e.content);
                        } else {
                            !items[2][e.fk_pm] && (items[2][e.fk_pm] = 0);
                            items[2][e.fk_pm]++;
                            !docData.extraOtherInfo[map.userName[e.fk_pm]] && (docData.extraOtherInfo[map.userName[e.fk_pm]] = []);
                            docData.extraOtherInfo[map.userName[e.fk_pm]].push(items[2][e.fk_pm] + ". " + e.content);
                        }
                    });

                    var filename = new Date().valueOf() + ".json";
                    var pyshell = new PythonShell('plugin/docx-generator.py', {mode: "text"});
                    fs.writeFileSync("plugin/" + filename, JSON.stringify(docData));
                    pyshell.send("plugin/" + filename);
                    pyshell.on('message', function (name) {
                        name = name.trim();
                        console.log("File Get :" + name);
                        res.render("downloadTpl",{path : '/temp/'+name.substring(9,name.length)});
                        setTimeout(function(){
                            fs.unlink(name.trim());
                        },MAX_W8);
                    });
                    pyshell.end(function (err) {
                        if (!!err) {
                            console.log(err);
                            return;
                        }
                        fs.unlink("plugin/"+filename);
                        console.log('Generate Doc Finished');
                    });
                });
            });
        });
    }
};